from fastapi import FastAPI, Header, HTTPException, Request
from typing import Optional, List, Dict, Any
from pydantic import BaseModel
from datetime import datetime
import uvicorn
import os
from pathlib import Path
import logging
from loguru import logger
import socket

logger = logging.getLogger(__name__)

app = FastAPI()

# 模拟数据
mock_persons = {
    "success": True,
    "data": {
        "pageData": [
            {
                "id": 6,
                "code": "L10000009",
                "name": "李星辰-1",
                "sex": 1,
                "birthday": "1994-01-23",
                "paperType": 111,
                "paperTypeName": "身份证",
                "paperNumber": "130***********2119",
                "paperAddress": "",
                "country": "CHN",
                "nation": 1,
                "nationName": "汉族",
                "email": "",
                "emailExt": "",
                "departmentId": 1,
                "departmentName": "安全管理部",
                "departmentNameExt": "安全管理部",
                "status": 1,
                "password": "0EE134963BC16FECCFCACBEC1FE90A77D2F3518816E94E5D0E37D7571769A2B1",
                "validStartTime": "2035-02-01 00:00:00",
                "validEndTime": "2025-02-02 23:59:59",
                "age": 31,
                "ownerCode": "001",
                "personIdentityId": 1,
                "personType": "0",
                "isAdmin": 0,
                "cards": [
                    {
                        "id": 14,
                        "cardNumber": "00000009",
                        "cardPassword": "123456",
                        "personId": 6,
                        "departmentId": 1,
                        "startDate": "2035-02-01 00:00:00",
                        "endDate": "2035-02-02 23:59:59",
                        "cardStatus": "0",
                        "validFlag": "ENABLE",
                        "category": "0",
                        "isMainCard": 1,
                        "isCoercion": 0
                    }
                ],
                "departmentList": [
                    {
                        "departmentId": 1,
                        "departmentType": 1,
                        "departmentName": "安全管理部",
                        "departmentNameExt": "安全管理部"
                    }
                ],
                "isBind": 0,
                "recordUpdateTime": 1740113214619
            },
             {
                "id": 6,
                "code": "L10000009",
                "name": "李星辰-1",
                "sex": 1,
                "birthday": "1994-01-23",
                "paperType": 111,
                "paperTypeName": "身份证",
                "paperNumber": "130***********2119",
                "paperAddress": "",
                "country": "CHN",
                "nation": 1,
                "nationName": "汉族",
                "email": "",
                "emailExt": "",
                "departmentId": 1,
                "departmentName": "安全管理部",
                "departmentNameExt": "安全管理部",
                "status": 1,
                "password": "0EE134963BC16FECCFCACBEC1FE90A77D2F3518816E94E5D0E37D7571769A2B1",
                "validStartTime": "2035-02-01 00:00:00",
                "validEndTime": "2025-02-02 23:59:59",
                "age": 31,
                "ownerCode": "001",
                "personIdentityId": 1,
                "personType": "0",
                "isAdmin": 0,
                "cards": [
                    {
                        "id": 14,
                        "cardNumber": "00000009",
                        "cardPassword": "123456",
                        "personId": 6,
                        "departmentId": 1,
                        "startDate": "2035-02-01 00:00:00",
                        "endDate": "2035-02-02 23:59:59",
                        "cardStatus": "0",
                        "validFlag": "ENABLE",
                        "category": "0",
                        "isMainCard": 1,
                        "isCoercion": 0
                    }
                ],
                "departmentList": [
                    {
                        "departmentId": 1,
                        "departmentType": 1,
                        "departmentName": "安全管理部",
                        "departmentNameExt": "安全管理部"
                    }
                ],
                "isBind": 0,
                "recordUpdateTime": 1740113214619
            },
              {
                "id": 6,
                "code": "L10000009",
                "name": "李星辰-1",
                "sex": 1,
                "birthday": "1994-01-23",
                "paperType": 111,
                "paperTypeName": "身份证",
                "paperNumber": "130***********2119",
                "paperAddress": "",
                "country": "CHN",
                "nation": 1,
                "nationName": "汉族",
                "email": "",
                "emailExt": "",
                "departmentId": 1,
                "departmentName": "安全管理部",
                "departmentNameExt": "安全管理部",
                "status": 1,
                "password": "0EE134963BC16FECCFCACBEC1FE90A77D2F3518816E94E5D0E37D7571769A2B1",
                "validStartTime": "2035-02-01 00:00:00",
                "validEndTime": "2025-02-02 23:59:59",
                "age": 31,
                "ownerCode": "001",
                "personIdentityId": 1,
                "personType": "0",
                "isAdmin": 0,
                "cards": [
                    {
                        "id": 14,
                        "cardNumber": "00000009",
                        "cardPassword": "123456",
                        "personId": 6,
                        "departmentId": 1,
                        "startDate": "2035-02-01 00:00:00",
                        "endDate": "2035-02-02 23:59:59",
                        "cardStatus": "0",
                        "validFlag": "ENABLE",
                        "category": "0",
                        "isMainCard": 1,
                        "isCoercion": 0
                    }
                ],
                "departmentList": [
                    {
                        "departmentId": 1,
                        "departmentType": 1,
                        "departmentName": "安全管理部",
                        "departmentNameExt": "安全管理部"
                    }
                ],
                "isBind": 0,
                "recordUpdateTime": 1740113214619
            },
               {
                "id": 6,
                "code": "L10000009",
                "name": "李星辰-1",
                "sex": 1,
                "birthday": "1994-01-23",
                "paperType": 111,
                "paperTypeName": "身份证",
                "paperNumber": "130***********2119",
                "paperAddress": "",
                "country": "CHN",
                "nation": 1,
                "nationName": "汉族",
                "email": "",
                "emailExt": "",
                "departmentId": 1,
                "departmentName": "安全管理部",
                "departmentNameExt": "安全管理部",
                "status": 1,
                "password": "0EE134963BC16FECCFCACBEC1FE90A77D2F3518816E94E5D0E37D7571769A2B1",
                "validStartTime": "2035-02-01 00:00:00",
                "validEndTime": "2025-02-02 23:59:59",
                "age": 31,
                "ownerCode": "001",
                "personIdentityId": 1,
                "personType": "0",
                "isAdmin": 0,
                "cards": [
                    {
                        "id": 14,
                        "cardNumber": "00000009",
                        "cardPassword": "123456",
                        "personId": 6,
                        "departmentId": 1,
                        "startDate": "2035-02-01 00:00:00",
                        "endDate": "2035-02-02 23:59:59",
                        "cardStatus": "0",
                        "validFlag": "ENABLE",
                        "category": "0",
                        "isMainCard": 1,
                        "isCoercion": 0
                    }
                ],
                "departmentList": [
                    {
                        "departmentId": 1,
                        "departmentType": 1,
                        "departmentName": "安全管理部",
                        "departmentNameExt": "安全管理部"
                    }
                ],
                "isBind": 0,
                "recordUpdateTime": 1740113214619
            },
                {
                "id": 6,
                "code": "L10000009",
                "name": "李星辰-1",
                "sex": 1,
                "birthday": "1994-01-23",
                "paperType": 111,
                "paperTypeName": "身份证",
                "paperNumber": "130***********2119",
                "paperAddress": "",
                "country": "CHN",
                "nation": 1,
                "nationName": "汉族",
                "email": "",
                "emailExt": "",
                "departmentId": 1,
                "departmentName": "安全管理部",
                "departmentNameExt": "安全管理部",
                "status": 1,
                "password": "0EE134963BC16FECCFCACBEC1FE90A77D2F3518816E94E5D0E37D7571769A2B1",
                "validStartTime": "2035-02-01 00:00:00",
                "validEndTime": "2025-02-02 23:59:59",
                "age": 31,
                "ownerCode": "001",
                "personIdentityId": 1,
                "personType": "0",
                "isAdmin": 0,
                "cards": [
                    {
                        "id": 14,
                        "cardNumber": "00000009",
                        "cardPassword": "123456",
                        "personId": 6,
                        "departmentId": 1,
                        "startDate": "2035-02-01 00:00:00",
                        "endDate": "2035-02-02 23:59:59",
                        "cardStatus": "0",
                        "validFlag": "ENABLE",
                        "category": "0",
                        "isMainCard": 1,
                        "isCoercion": 0
                    }
                ],
                "departmentList": [
                    {
                        "departmentId": 1,
                        "departmentType": 1,
                        "departmentName": "安全管理部",
                        "departmentNameExt": "安全管理部"
                    }
                ],
                "isBind": 0,
                "recordUpdateTime": 1740113214619
            },
                 {
                "id": 6,
                "code": "L10000009",
                "name": "李星辰-1",
                "sex": 1,
                "birthday": "1994-01-23",
                "paperType": 111,
                "paperTypeName": "身份证",
                "paperNumber": "130***********2119",
                "paperAddress": "",
                "country": "CHN",
                "nation": 1,
                "nationName": "汉族",
                "email": "",
                "emailExt": "",
                "departmentId": 1,
                "departmentName": "安全管理部",
                "departmentNameExt": "安全管理部",
                "status": 1,
                "password": "0EE134963BC16FECCFCACBEC1FE90A77D2F3518816E94E5D0E37D7571769A2B1",
                "validStartTime": "2035-02-01 00:00:00",
                "validEndTime": "2025-02-02 23:59:59",
                "age": 31,
                "ownerCode": "001",
                "personIdentityId": 1,
                "personType": "0",
                "isAdmin": 0,
                "cards": [
                    {
                        "id": 14,
                        "cardNumber": "00000009",
                        "cardPassword": "123456",
                        "personId": 6,
                        "departmentId": 1,
                        "startDate": "2035-02-01 00:00:00",
                        "endDate": "2035-02-02 23:59:59",
                        "cardStatus": "0",
                        "validFlag": "ENABLE",
                        "category": "0",
                        "isMainCard": 1,
                        "isCoercion": 0
                    }
                ],
                "departmentList": [
                    {
                        "departmentId": 1,
                        "departmentType": 1,
                        "departmentName": "安全管理部",
                        "departmentNameExt": "安全管理部"
                    }
                ],
                "isBind": 0,
                "recordUpdateTime": 1740113214619
            },
                  {
                "id": 6,
                "code": "L10000009",
                "name": "李星辰-1",
                "sex": 1,
                "birthday": "1994-01-23",
                "paperType": 111,
                "paperTypeName": "身份证",
                "paperNumber": "130***********2119",
                "paperAddress": "",
                "country": "CHN",
                "nation": 1,
                "nationName": "汉族",
                "email": "",
                "emailExt": "",
                "departmentId": 1,
                "departmentName": "安全管理部",
                "departmentNameExt": "安全管理部",
                "status": 1,
                "password": "0EE134963BC16FECCFCACBEC1FE90A77D2F3518816E94E5D0E37D7571769A2B1",
                "validStartTime": "2035-02-01 00:00:00",
                "validEndTime": "2025-02-02 23:59:59",
                "age": 31,
                "ownerCode": "001",
                "personIdentityId": 1,
                "personType": "0",
                "isAdmin": 0,
                "cards": [
                    {
                        "id": 14,
                        "cardNumber": "00000009",
                        "cardPassword": "123456",
                        "personId": 6,
                        "departmentId": 1,
                        "startDate": "2035-02-01 00:00:00",
                        "endDate": "2035-02-02 23:59:59",
                        "cardStatus": "0",
                        "validFlag": "ENABLE",
                        "category": "0",
                        "isMainCard": 1,
                        "isCoercion": 0
                    }
                ],
                "departmentList": [
                    {
                        "departmentId": 1,
                        "departmentType": 1,
                        "departmentName": "安全管理部",
                        "departmentNameExt": "安全管理部"
                    }
                ],
                "isBind": 0,
                "recordUpdateTime": 1740113214619
            },
            {
                "id": 5,
                "code": "L000006",
                "name": "李星辰1",
                "sex": 1,
                "birthday": "1960-08-04",
                "paperType": 111,
                "paperTypeName": "身份证",
                "paperNumber": "130***********037X",
                "paperAddress": "",
                "country": "CHN",
                "nation": 1,
                "nationName": "汉族",
                "email": "",
                "emailExt": "",
                "departmentId": 2,
                "departmentName": "临时作业",
                "departmentNameExt": "临时作业",
                "status": 1,
                "password": "C6B51A43DBD424220836F43DC21B2940F4F24E28220BB6D9C489738AA7C0E491",
                "validStartTime": "2025-02-13 00:00:00",
                "validEndTime": "2035-02-13 23:59:59",
                "age": 64,
                "ownerCode": "001",
                "personIdentityId": 1,
                "personType": "0",
                "isAdmin": 0,
                "cards": [
                    {
                        "id": 12,
                        "cardNumber": "00000006",
                        "cardPassword": "123456",
                        "personId": 5,
                        "departmentId": 2,
                        "startDate": "2025-02-13 00:00:00",
                        "endDate": "2035-02-13 23:59:59",
                        "cardStatus": "0",
                        "validFlag": "ENABLE",
                        "category": "1",
                        "isMainCard": 0,
                        "isCoercion": 0
                    },
                    {
                        "id": 15,
                        "cardNumber": "00000001",
                        "cardPassword": "123456",
                        "personId": 5,
                        "departmentId": 2,
                        "startDate": "2025-02-13 00:00:00",
                        "endDate": "2035-02-13 23:59:59",
                        "cardStatus": "0",
                        "validFlag": "ENABLE",
                        "category": "0",
                        "isMainCard": 1,
                        "isCoercion": 0
                    }
                ],
                "departmentList": [
                    {
                        "departmentId": 2,
                        "departmentType": 1,
                        "departmentName": "临时作业",
                        "departmentNameExt": "临时作业"
                    }
                ],
                "isBind": 0,
                "recordUpdateTime": 1740107785656
            },
            {
                "id": 4,
                "code": "L00000008",
                "name": "苏良-5",
                "sex": 2,
                "birthday": "1986-04-07",
                "paperType": 111,
                "paperTypeName": "身份证",
                "paperNumber": "211***********4622",
                "paperAddress": "",
                "country": "CHN",
                "nation": 1,
                "nationName": "汉族",
                "email": "",
                "emailExt": "",
                "departmentId": 2,
                "departmentName": "临时作业",
                "departmentNameExt": "临时作业",
                "status": 1,
                "password": "F760B4B209BDC200B977C03912E25DB93EFFCDA052B7EB20ACC33A8F4F9041DF",
                "validStartTime": "2025-01-08 00:00:00",
                "validEndTime": "2035-01-08 23:59:59",
                "age": 38,
                "ownerCode": "001",
                "personIdentityId": 1,
                "personType": "0",
                "isAdmin": 0,
                "cards": [
                    {
                        "id": 8,
                        "cardNumber": "50000000",
                        "cardPassword": "123456",
                        "personId": 4,
                        "departmentId": 2,
                        "startDate": "2025-01-08 00:00:00",
                        "endDate": "2035-01-08 23:59:59",
                        "cardStatus": "0",
                        "validFlag": "ENABLE",
                        "category": "0",
                        "isMainCard": 1,
                        "isCoercion": 0
                    },
                    {
                        "id": 10,
                        "cardNumber": "00000005",
                        "cardPassword": "123456",
                        "personId": 4,
                        "departmentId": 2,
                        "startDate": "2025-01-08 00:00:00",
                        "endDate": "2035-01-08 23:59:59",
                        "cardStatus": "0",
                        "validFlag": "ENABLE",
                        "category": "1",
                        "isMainCard": 0,
                        "isCoercion": 0
                    }
                ],
                "departmentList": [
                    {
                        "departmentId": 2,
                        "departmentType": 1,
                        "departmentName": "临时作业",
                        "departmentNameExt": "临时作业"
                    }
                ],
                "isBind": 0,
                "recordUpdateTime": 1740106350604
            },
            {
                "id": 3,
                "code": "L00000004",
                "name": "苏良4",
                "sex": 1,
                "birthday": "2013-11-08",
                "paperType": 111,
                "paperTypeName": "身份证",
                "paperNumber": "130***********091X",
                "paperAddress": "",
                "country": "CHN",
                "nation": 1,
                "nationName": "汉族",
                "email": "",
                "emailExt": "",
                "departmentId": 2,
                "departmentName": "临时作业",
                "departmentNameExt": "临时作业",
                "status": 1,
                "password": "4C438F1AC5F2D1537EE0CC845362615C02E04E2F2445A08E3A40A67E6AACB32D",
                "validStartTime": "2025-01-08 00:00:00",
                "validEndTime": "2035-01-08 23:59:59",
                "age": 11,
                "ownerCode": "001",
                "personIdentityId": 1,
                "personType": "0",
                "isAdmin": 0,
                "cards": [
                    {
                        "id": 6,
                        "cardNumber": "200000000",
                        "cardPassword": "123456",
                        "personId": 3,
                        "departmentId": 2,
                        "startDate": "2025-01-08 00:00:00",
                        "endDate": "2035-01-08 23:59:59",
                        "cardStatus": "0",
                        "validFlag": "ENABLE",
                        "category": "0",
                        "isMainCard": 1,
                        "isCoercion": 0
                    },
                    {
                        "id": 7,
                        "cardNumber": "00000004",
                        "cardPassword": "123456",
                        "personId": 3,
                        "departmentId": 2,
                        "startDate": "2025-01-08 00:00:00",
                        "endDate": "2035-01-08 23:59:59",
                        "cardStatus": "0",
                        "validFlag": "ENABLE",
                        "category": "1",
                        "isMainCard": 0,
                        "isCoercion": 0
                    }
                ],
                "departmentList": [
                    {
                        "departmentId": 2,
                        "departmentType": 1,
                        "departmentName": "临时作业",
                        "departmentNameExt": "临时作业"
                    }
                ],
                "isBind": 0,
                "recordUpdateTime": 1739419150676
            }
        ],
        "currentPage": 1,
        "totalPage": 1,
        "pageSize": 10,
        "totalRows": 14
    },
    "code": "0",
    "errMsg": ""
}

mock_identities = {
    "success": True,
    "data": {
        "value": [
            {
                "id": 1,
                "name": "默认身份",
                "description": "默认身份",
                "validFlag": "ENABLE"
            },
            {
                "id": 2,
                "name": "待入职",
                "description": "待入职", 
                "validFlag": "ENABLE"
            },
            {
                "id": 3,
                "name": "正式员工",
                "description": "正式员工",
                "validFlag": "ENABLE"
            },
            {
                "id": 4,
                "name": "临时工",
                "description": "临时工作人员",
                "validFlag": "ENABLE"
            },
            {
                "id": 5,
                "name": "实习生",
                "description": "实习人员",
                "validFlag": "ENABLE"
            }
        ]
    },
    "code": "0",
    "errMsg": ""
}

mock_departments = {
    "success": True,
    "data": {
        "value": [
            {
                "id": 1,
                "parentId": 0,
                "name": "安全管理部",
                "nameExt": "安全管理部",
                "checkStat": 1,
                "sort": 1,
                "isParent": 1,
                "parentIds": "1,",
                "nodeType": 1
            },
            {
                "id": 2,
                "parentId": 1,
                "name": "临时作业",
                "nameExt": "临时作业",
                "checkStat": 1,
                "sort": 1,
                "isParent": 0
            },
            {
                "id": 3,
                "parentId": 1,
                "name": "安全部",
                "nameExt": "安全部",
                "checkStat": 1,
                "sort": 2,
                "isParent": 0
            },
            {
                "id": 4,
                "parentId": 1,
                "name": "固废生产",
                "nameExt": "固废生产",
                "checkStat": 1,
                "sort": 3,
                "isParent": 0
            },
            # ... 其他部门数据
        ]
    },
    "code": "0",
    "errMsg": ""
}

# 使用生成的有效RSA公钥
mock_public_key = {
    "success": True,
    "data": {
        "publicKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvpRPL5+rV5uHI5M4FDYVKGxja0F2zgJgQzGn6" +
                    "vxiYC+FxcxzIGaL4sJoQnKe2DOHpGXZK6LFVOr0VSx7r3KwGXBcN5QNF6FiGzXHCQO5DG7P3Z9gs" +
                    "Qb0QlS9GDcGOXgBuZlZHVUS4N5FGlPKvJI+N9Hh2r3C4TKDNpjgB0y2c4QIDAQAB"
    },
    "code": "0",
    "errMsg": ""
}

mock_token = {
    "success": True,
    "data": {
        "accessToken": "mock_access_token",
        "refreshToken": "mock_refresh_token",
        "expireTime": 7200
    },
    "code": "0",
    "errMsg": ""
}

# 请求模型
class PersonSearchRequest(BaseModel):
    searchKey: str = ""
    pageNum: int
    pageSize: int
    departmentId: int
    isContain: bool
    statusList: List[int]

class PersonCreateRequest(BaseModel):
    name: str
    departmentName: str
    code: str
    paperType: int
    paperNumber: str
    sex: int
    birthday: str
    personIdentityId: int
    age: int
    nation: int
    country: str
    personType: str
    isAdmin: int
    departmentId: int
    departmentList: List[Dict[str, Any]]
    validStartTime: str
    validEndTime: str
    cards: List[Dict[str, Any]]
    status: int
    phone: Optional[str] = None

class PersonDeleteRequest(BaseModel):
    openDeleteFlag: int
    deleteCardFlag: int
    departmentId: int
    ids: List[int]

class TokenRequest(BaseModel):
    grant_type: str
    username: str
    password: str
    client_id: str
    client_secret: str
    public_key: str

class PersonIdentityResponse(BaseModel):
    success: bool = True
    data: Dict[str, List[Dict[str, Any]]]
    code: str = "0"
    errMsg: str = ""

# 调试中间件
@app.middleware("http")
async def log_requests(request: Request, call_next):
    logger.debug(f"收到请求: {request.method} {request.url.path}")
    logger.debug(f"请求头: {request.headers}")
    response = await call_next(request)
    return response

# 路由定义
@app.get("/evo-apigw/evo-oauth/1.0.0/oauth/public-key", name="get_public_key")
async def get_public_key():
    """获取公钥接口"""
    logger.debug("处理公钥请求")
    return {
        "success": True,
        "data": {
            "publicKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvpRPL5+rV5uHI5M4FDYVKGxja0F2zgJgQzGn6" +
                        "vxiYC+FxcxzIGaL4sJoQnKe2DOHpGXZK6LFVOr0VSx7r3KwGXBcN5QNF6FiGzXHCQO5DG7P3Z9gs" +
                        "Qb0QlS9GDcGOXgBuZlZHVUS4N5FGlPKvJI+N9Hh2r3C4TKDNpjgB0y2c4QIDAQAB"
        },
        "code": "0",
        "errMsg": ""
    }

@app.post("/evo-apigw/evo-oauth/1.0.0/oauth/extend/token", name="get_token")
async def get_token(request: Request):
    """获取访问令牌接口"""
    # 获取请求体
    try:
        body = await request.json()
        logger.debug(f"处理token请求: {body}")
    except:
        body = {}
        
    return {
        "success": True,
        "data": {
            "access_token": "mock_access_token",
            "refresh_token": "mock_refresh_token",
            "expires_in": 7200
        },
        "code": "0",
        "errMsg": ""
    }

@app.post("/evo-apigw/evo-brm/1.2.0/person/page")
async def get_person_list(
    request: PersonSearchRequest,
    authorization: Optional[str] = Header(None)
):
    return mock_persons

@app.get("/evo-apigw/evo-brm/1.2.0/person/identity", response_model=PersonIdentityResponse)
async def get_person_identities(authorization: Optional[str] = Header(None)):
    """获取人员身份列表"""
    if not authorization or not authorization.startswith("bearer "):
        raise HTTPException(status_code=401, detail="Unauthorized")
        
    # 模拟人员身份数据
    identities = [
        {
            "id": 1,
            "name": "默认身份",
            "description": "默认身份",
            "validFlag": "ENABLE"
        },
        {
            "id": 2,
            "name": "待入职",
            "description": "待入职",
            "validFlag": "ENABLE"
        },
        {
            "id": 3,
            "name": "正式员工",
            "description": "正式员工",
            "validFlag": "ENABLE"
        },
        {
            "id": 4,
            "name": "临时工",
            "description": "临时工作人员",
            "validFlag": "ENABLE"
        },
        {
            "id": 5,
            "name": "实习生",
            "description": "实习人员",
            "validFlag": "ENABLE"
        }
    ]
    
    return {
        "success": True,
        "data": {
            "value": identities
        },
        "code": "0",
        "errMsg": ""
    }

@app.post("/evo-apigw/evo-brm/1.2.0/department/tree")
async def get_department_tree(
    authorization: Optional[str] = Header(None)
):
    return mock_departments

@app.post("/evo-apigw/evo-brm/1.2.0/person")
async def create_person(
    request: PersonCreateRequest,
    authorization: Optional[str] = Header(None)
):
    """创建人员信息"""
    if not authorization or not authorization.startswith("bearer "):
        raise HTTPException(status_code=401, detail="Unauthorized")
    
    # 模拟身份证号重复检查
    if request.paperNumber == "211422198604074622":
        return {
            "success": False,
            "data": {},
            "code": "28160001",
            "errMsg": "证件号码已存在"
        }
    
    # 模拟卡号重复检查
    if request.cards and request.cards[0]["cardNumber"] == "00000001":
        return {
            "success": False,
            "data": {},
            "code": "28160002",
            "errMsg": "卡号已存在"
        }
    
    # 模拟成功响应
    return {
        "success": True,
        "data": {
            "id": len(mock_persons["data"]["pageData"]) + 1  # 生成新的ID
        },
        "code": "0",
        "errMsg": ""
    }

@app.post("/evo-apigw/evo-brm/1.2.0/person/delete")
async def delete_person(
    request: PersonDeleteRequest,
    authorization: Optional[str] = Header(None)
):
    return {
        "success": True,
        "data": {},
        "code": "0",
        "errMsg": ""
    }

@app.get("/evo-apigw/evo-brm/1.2.0/person/recycle/paper")
async def check_paper_number(
    paperType: int,
    paperNumber: str,
    authorization: Optional[str] = Header(None)
):
    """检查身份证号是否重复"""
    if not authorization or not authorization.startswith("bearer "):
        raise HTTPException(status_code=401, detail="Unauthorized")
    
    # 模拟身份证号重复检查
    duplicate_numbers = [
        "211422198604074622",  # 已存在的身份证号
        "130102196902101826",  # 另一个已存在的身份证号
    ]
    
    if paperNumber in duplicate_numbers:
        return {
            "success": False,
            "data": {},
            "code": "28160001",
            "errMsg": "证件号码已存在"
        }
    
    return {
        "success": True,
        "data": {},
        "code": "0",
        "errMsg": ""
    }

@app.get("/evo-apigw/evo-brm/1.2.0/person/{person_id}")
async def get_person_detail(
    person_id: int,
    authorization: Optional[str] = Header(None)
):
    """获取人员详情"""
    if not authorization or not authorization.startswith("bearer "):
        raise HTTPException(status_code=401, detail="Unauthorized")
        
    # 从模拟数据中查找对应ID的人员
    persons = mock_persons.get("data", {}).get("pageData", [])
    person = next((p for p in persons if p["id"] == person_id), None)
    
    if not person:
        return {
            "success": False,
            "data": None,
            "code": "28160004",
            "errMsg": "未找到该人员信息"
        }
    
    # 返回详细信息
    return {
        "success": True,
        "data": {
            "id": person_id,
            "code": person.get("code", ""),
            "name": person.get("name", ""),
            "sex": person.get("sex", 1),
            "birthday": person.get("birthday", ""),
            "paperType": person.get("paperType", 111),
            "paperTypeName": "身份证",
            "paperNumber": person.get("paperNumber", ""),
            "paperAddress": "",
            "country": "CHN",
            "nation": 1,
            "nationName": "汉族",
            "phone": person.get("phone", ""),
            "email": "",
            "emailExt": "",
            "departmentId": person.get("departmentId", 1),
            "departmentName": person.get("departmentName", ""),
            "departmentNameExt": person.get("departmentName", ""),
            "status": 1,
            "password": "6B5862797B5E3A3CE9030DB0AF9301DCE0BE0D26D8B4197EBF8A72FD028DADDE",
            "validStartTime": person.get("validStartTime", "2025-01-08 00:00:00"),
            "validEndTime": person.get("validEndTime", "2035-01-08 23:59:59"),
            "age": person.get("age", 30),
            "ownerCode": "001",
            "personIdentityId": person.get("personIdentityId", 1),
            "personType": "0",
            "isAdmin": 0,
            "cards": person.get("cards", [
                {
                    "id": person_id * 2,
                    "cardNumber": person.get("cards", [{}])[0].get("cardNumber", ""),
                    "cardPassword": "123456",
                    "personId": person_id,
                    "departmentId": person.get("departmentId", 1),
                    "startDate": person.get("validStartTime", "2025-01-08 00:00:00"),
                    "endDate": person.get("validEndTime", "2035-01-08 23:59:59"),
                    "cardStatus": "0",
                    "validFlag": "ENABLE",
                    "category": "0",
                    "isMainCard": 1,
                    "isCoercion": 0
                }
            ]),
            "fieldExt": {
                "businessType": "4"
            },
            "parentIds": "1,2,",
            "departmentList": [
                {
                    "departmentId": person.get("departmentId", 1),
                    "departmentType": 1,
                    "departmentName": person.get("departmentName", ""),
                    "departmentNameExt": person.get("departmentName", "")
                }
            ],
            "isBind": 0,
            "recordUpdateTime": 1740106350604
        },
        "code": "0",
        "errMsg": ""
    }

if __name__ == "__main__":
    # 检查端口是否被占用
    def is_port_in_use(port):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            try:
                s.bind(('127.0.0.1', port))
                return False
            except socket.error:
                return True
    
    # 寻找可用端口
    port = 8000
    while is_port_in_use(port) and port < 8100:
        port += 1
    
    if port >= 8100:
        print("Error: 无法找到可用端口(8000-8099)")
        exit(1)
        
    print(f"Starting mock server on http://127.0.0.1:{port}")
    
    # 配置 uvicorn 的日志级别和其他选项
    config = uvicorn.Config(
        app=app,
        host="127.0.0.1",
        port=port,
        log_level="info",
        access_log=True,
        reload=True  # 开发模式下自动重载
    )
    
    try:
        server = uvicorn.Server(config)
        server.run()
    except Exception as e:
        print(f"启动 mock server 失败: {e}") 